package com.jinbiao.quasar.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.model.SysLogLogin;
import com.jinbiao.quasar.util.AjaxJson;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.Page;

import java.util.List;

@Controller
@OperationLog
public class LogLoginController {
    @Db
    SqlToyLazyDao dao;
    @Mapping("/log/get-log-login-list")
    public AjaxJson getLogLoginList(int page,int pageSize,String sortBy,boolean desc,SysLogLogin sysLogLogin){
        String sqlTemplate = "SELECT * FROM sys_log_login WHERE" +
                "            #[and login_username=:loginUsername]" +
                "            #[and login_ip=:loginIp]" +
                "            #[and login_browser=:loginBrowser]" +
                "            #[and login_os=:loginOs]" +
                "            #[and login_platform=:loginPlatform]" +
                "            #[and login_success=:loginSuccess]" +
                " order by {} {}";
        String sql = StrUtil.format(sqlTemplate, sortBy, desc ? "desc" : "asc");
        Page<SysLogLogin> pageResult =  dao.findPageBySql(new Page(pageSize, page), sql, BeanUtil.beanToMap(sysLogLogin),SysLogLogin.class);
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/log/delete-log-login-by-id")
    public AjaxJson deleteLogLoginById(SysLogLogin sysLogLogin){
        return AjaxJson.getSuccessData(dao.delete(sysLogLogin));
    }

    @Mapping("/log/edit-log")
    public AjaxJson editLogLogin(SysLogLogin sysLogLogin){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysLogLogin));
    }

    @Mapping("/log/add-log")
    public AjaxJson addLogLogin(SysLogLogin sysLogLogin){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysLogLogin));
    }

    @Mapping("/log/query-log-login-by-id")
    public AjaxJson queryLogLoginById(SysLogLogin sysLogLogin){
        List<SysLogLogin> results = dao.findBySql("sysLogLoginList",sysLogLogin);
        if(CollectionUtil.isNotEmpty(results)){
            SysLogLogin configBackend = results.get(0);
            return AjaxJson.getSuccessData(configBackend);
        }
        return AjaxJson.getSuccessData(null);
    }

    @Mapping("/public/get-log-login-all")
    public AjaxJson getLogLoginAll(SysLogLogin sysLogLogin){
        return AjaxJson.getSuccessData(dao.findBySql("sysLogLoginList",sysLogLogin));
    }
}
